'use strict';

const Service = require('egg').Service;

class ClothingService extends Service {
  // 获取衣服列表
  async getList(userId, options = {}) {
    const { Op } = this.app.Sequelize;
    const { page = 1, pageSize = 20, category_id, color, season, style, status, keyword, is_favorite } = options;
    
    const where = { user_id: userId };
    
    // 构建查询条件
    if (category_id) {
      where.category_id = category_id;
    }
    
    if (color) {
      where.color = color;
    }
    
    if (season) {
      where.season = season;
    }
    
    if (style) {
      where.style = style;
    }
    
    if (status) {
      where.status = status;
    }
    
    if (is_favorite !== undefined) {
      where.is_favorite = is_favorite === true || is_favorite === 'true';
    }

    if (keyword) {
      where[Op.or] = [
        { name: { [Op.like]: `%${keyword}%` } },
        { brand: { [Op.like]: `%${keyword}%` } },
        { notes: { [Op.like]: `%${keyword}%` } },
      ];
    }

    const offset = (page - 1) * pageSize;
    
    const result = await this.ctx.model.Clothing.findAndCountAll({
      where,
      // 暂时移除关联查询，避免deleted_at字段问题
      // include: [
      //   {
      //     model: this.ctx.model.Category,
      //     as: 'category',
      //     attributes: ['id', 'name', 'name_en'],
      //   },
      // ],
      order: [['created_at', 'DESC']],
      limit: pageSize,
      offset,
    });

    return {
      list: result.rows,
      total: result.count,
      page,
      pageSize,
      totalPages: Math.ceil(result.count / pageSize),
    };
  }

  // 根据ID查找衣服
  async findById(id, userId) {
    return await this.ctx.model.Clothing.findOne({
      where: { id, user_id: userId },
      // 暂时移除关联查询，避免deleted_at字段问题
      // include: [
      //   {
      //     model: this.ctx.model.Category,
      //     as: 'category',
      //     attributes: ['id', 'name', 'name_en'],
      //   },
      //   {
      //     model: this.ctx.model.Tag,
      //     as: 'tags',
      //     attributes: ['id', 'name', 'type', 'color'],
      //     through: { attributes: [] },
      //   },
      // ],
    });
  }

  // 创建衣服
  async create(clothingData) {
    const { tags, ...data } = clothingData;
    
    const clothing = await this.ctx.model.Clothing.create(data);
    
    // 如果有标签，添加标签关联
    if (tags && tags.length > 0) {
      await this.addTags(clothing.id, tags);
    }
    
    return await this.findById(clothing.id, data.user_id);
  }

  // 根据ID更新衣服
  async updateById(id, updateData) {
    const { tags, ...data } = updateData;
    
    await this.ctx.model.Clothing.update(data, {
      where: { id },
    });
    
    // 如果有标签更新，先删除旧标签再添加新标签
    if (tags !== undefined) {
      await this.ctx.model.ClothingTag.destroy({
        where: { clothing_id: id },
      });
      
      if (tags.length > 0) {
        await this.addTags(id, tags);
      }
    }
    
    return true;
  }

  // 根据ID删除衣服
  async deleteById(id) {
    // 删除相关的标签关联
    await this.ctx.model.ClothingTag.destroy({
      where: { clothing_id: id },
    });
    
    // 删除相关的搭配关联
    await this.ctx.model.OutfitItem.destroy({
      where: { clothing_id: id },
    });
    
    // 软删除衣服
    return await this.ctx.model.Clothing.destroy({
      where: { id },
    });
  }

  // 添加标签
  async addTags(clothingId, tagIds) {
    const tagRelations = tagIds.map(tagId => ({
      clothing_id: clothingId,
      tag_id: tagId,
    }));
    
    return await this.ctx.model.ClothingTag.bulkCreate(tagRelations);
  }

  // 移除标签
  async removeTags(clothingId, tagIds) {
    return await this.ctx.model.ClothingTag.destroy({
      where: {
        clothing_id: clothingId,
        tag_id: { [this.app.Sequelize.Op.in]: tagIds },
      },
    });
  }

  // 获取衣服统计信息
  async getStats(userId) {
    const { Op } = this.app.Sequelize;
    
    // 按分类统计
    const categoryStats = await this.ctx.model.Clothing.findAll({
      where: { user_id: userId },
      attributes: [
        'category_id',
        [this.app.Sequelize.fn('COUNT', this.app.Sequelize.col('id')), 'count'],
      ],
      include: [
        {
          model: this.ctx.model.Category,
          as: 'category',
          attributes: ['name'],
        },
      ],
      group: ['category_id'],
    });

    // 按颜色统计
    const colorStats = await this.ctx.model.Clothing.findAll({
      where: { 
        user_id: userId,
        color: { [Op.ne]: null },
      },
      attributes: [
        'color',
        [this.app.Sequelize.fn('COUNT', this.app.Sequelize.col('id')), 'count'],
      ],
      group: ['color'],
      order: [[this.app.Sequelize.fn('COUNT', this.app.Sequelize.col('id')), 'DESC']],
    });

    // 按季节统计
    const seasonStats = await this.ctx.model.Clothing.findAll({
      where: { 
        user_id: userId,
        season: { [Op.ne]: null },
      },
      attributes: [
        'season',
        [this.app.Sequelize.fn('COUNT', this.app.Sequelize.col('id')), 'count'],
      ],
      group: ['season'],
    });

    // 按状态统计
    const statusStats = await this.ctx.model.Clothing.findAll({
      where: { user_id: userId },
      attributes: [
        'status',
        [this.app.Sequelize.fn('COUNT', this.app.Sequelize.col('id')), 'count'],
      ],
      group: ['status'],
    });

    return {
      category: categoryStats,
      color: colorStats,
      season: seasonStats,
      status: statusStats,
    };
  }

  // 获取推荐衣服（基于用户偏好和历史记录）
  async getRecommendations(userId, options = {}) {
    const { limit = 10, excludeIds = [] } = options;
    const { Op } = this.app.Sequelize;
    
    // 获取用户偏好
    const preferences = await this.service.user.getPreferences(userId);
    const stylePreferences = preferences.filter(p => p.preference_type === 'style');
    const colorPreferences = preferences.filter(p => p.preference_type === 'color');
    
    const where = { 
      user_id: userId,
      status: 'available',
    };
    
    if (excludeIds.length > 0) {
      where.id = { [Op.notIn]: excludeIds };
    }
    
    // 基于偏好构建查询条件
    if (stylePreferences.length > 0) {
      const preferredStyles = stylePreferences.map(p => p.preference_key);
      where.style = { [Op.in]: preferredStyles };
    }
    
    return await this.ctx.model.Clothing.findAll({
      where,
      include: [
        {
          model: this.ctx.model.Category,
          as: 'category',
          attributes: ['id', 'name'],
        },
      ],
      order: [
        ['wear_count', 'ASC'], // 优先推荐穿着次数少的
        ['created_at', 'DESC'],
      ],
      limit,
    });
  }
}

module.exports = ClothingService;
